package com.ruoyi.web.controller.admin;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CullenUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.module.domain.Account;
import com.ruoyi.module.domain.FundDetails;
import com.ruoyi.module.mapper.FundDetailsMapper;
import com.ruoyi.module.po.RestoreOrTransferUserPo;
import com.ruoyi.module.service.IAccountService;
import com.ruoyi.module.service.IFundDetailsService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.List;

/**
 * 用户信息Controller
 *
 * @author fubojin
 * @date 2024-12-17
 */
@RestController
@RequestMapping("/admin/user")
public class AdminSysUserController extends BaseController {
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private IAccountService accountService;

    @Autowired
    private IFundDetailsService fundDetailsService;

    /**
     * 后管端查询信息列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysUser sysUser) {
        startPage();
//        sysUser.setRoleId(102L);
        List<SysUser> list = sysUserService.selectUserList(sysUser);
        return getDataTable(list);
    }

    /**
     * 后管端查询用户（员工）信息列表
     */
    @GetMapping("/listUser")
    public TableDataInfo listUser(SysUser sysUser) {
        startPage();
        List<SysUser> list = sysUserService.selectUserAdminList(sysUser);
        return getDataTable(list);
    }

    /**
     * 后管端查询（客户）信息列表
     */
    @GetMapping("/listCustomer")
    public TableDataInfo listCustomer(SysUser sysUser) {
        startPage();
        List<SysUser> list = sysUserService.listCustomer(sysUser);
        return getDataTable(list);
    }

    /**
     * 查询删除用户信息列表
     */
    @GetMapping("/deleteUserList")
    public TableDataInfo deleteUserList(SysUser sysUser) {
        startPage();
//        sysUser.setRoleId(101L);//客户
        List<SysUser> list = sysUserService.selectDeleteUserList(sysUser);
        return getDataTable(list);
    }


    /**
     * 导出用户信息列表
     */
    @Log(title = "用户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser sysUser) {
        List<SysUser> list = sysUserService.selectUserList(sysUser);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户信息数据");
    }

    /**
     * 获取用户信息详细信息
     */
    @GetMapping(value = "/{userId}")
    public AjaxResult getInfo(@PathVariable("userId") Long userId) {
        SysUser sysUser = sysUserService.selectUserById(userId);
        Account account = accountService.selectAccountByUserId(userId);
        if (account != null) {
            sysUser.setOpenName(account.getOpenName());
            sysUser.setOpeningBank(account.getOpeningBank());
            sysUser.setBankAccount(account.getBankAccount());
            sysUser.setCreditGold(account.getCreditGold());
            sysUser.setPassword(SecurityUtils.encryptPassword(sysUser.getPassword()));
        }
        return success(sysUser);
    }

    /**
     * 获取用户信息详细信息
     */
    @GetMapping(value = "/selectUserByPhone")
    public AjaxResult selectUserByPhone(@RequestParam String phone) {
        SysUser sysUser = sysUserService.selectUserByPhone(phone);
        return success(sysUser);
    }

    /**
     * 新增客户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysUser user) {
        if (!sysUserService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysUserService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }

        user.setCreateBy(getUsername());
        String password = user.getPassword();
        if (password == null) {
            password = "123456";
        }
        user.setPassword(SecurityUtils.encryptPassword(password));
        return toAjax(sysUserService.insertUser(user));
    }

    /**
     * 新增员工信息
     */
    @Log(title = "用户信息", businessType = BusinessType.INSERT)
    @PostMapping("/addUser")
    public AjaxResult addUser(@RequestBody SysUser user) {
        if (!sysUserService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !sysUserService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }

        user.setCreateBy(getUsername());
        String password = user.getPassword();
        if (password == null) {
            password = "123456";
        }
        SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
        SysDept companyDept = sysDeptService.selectDeptById(user.getCompanyId());
        Integer level = sysDept.getLevel();

        //校验是否能设置管理员
        if (user.getEmployeeType() == 1) {
            CullenUtils.validateDataThrowException(level != 1, "所属小组不是经销商不能设置为分公司管理员！");
            CullenUtils.validateDataThrowException(sysDept.getUserId() != null, "该分公司: " + sysDept.getDeptName() + " 已存在管理员：" + sysDept.getLeader() + "！");
        }

        if (user.getSigningRatio() != null && level != null && (level == 1 || level == 0)) {
            user.setSigningRatio(25);//默认公司和分公司25%
        }
        user.setLevel(level);
        user.setPassword(SecurityUtils.encryptPassword(password));
        int i = sysUserService.insertUser(user);
        if (level != null && level == 1 && user.getEmployeeType() == 1) {//经销商且管理员才需要
            //添加银行账户及保证金信息
            Account account = new Account();
            account.setUserId(user.getUserId());
            account.setOpenName(user.getOpenName());
            account.setOpeningBank(user.getOpeningBank());
            account.setBankAccount(user.getBankAccount());
            BigDecimal credit = user.getCreditGold() == null ? new BigDecimal(0) : user.getCreditGold();
            account.setCreditGold(credit);
            accountService.insertAccount(account);

            //添加资金明细（保证金）
            FundDetails fundDetails = new FundDetails();
            fundDetails.setUserId(user.getUserId());
            fundDetails.setDeptId(companyDept.getDeptId());
            fundDetails.setDeptName(companyDept.getDeptName());
            fundDetails.setFundType(4);
            fundDetails.setVariableAmount(credit);
            fundDetailsService.insertFundDetails(fundDetails);

            //添加该管理员为分公司负责人
            companyDept.setUserId(user.getUserId());
            companyDept.setLeader(user.getNickName());
            companyDept.setPhone(user.getUserPhone());
            sysDeptService.updateDept(companyDept);

        }
        return toAjax(i);
    }

    /**
     * 修改用户信息（客户修改）
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysUser user) {
        return toAjax(sysUserService.updateUser(user));
    }

    /**
     * 修改用户信息（员工修改）
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateUser")
    public AjaxResult updateUser(@RequestBody SysUser user) {

        SysUser selectUser = sysUserService.selectUserById(user.getUserId());
        SysDept sysDept = sysDeptService.selectDeptById(user.getDeptId());
        Integer level = sysDept.getLevel();
        user.setLevel(level);
        if (level == 1 && user.getEmployeeType() == 1) {

            if (sysDept.getUserId() != null && !user.getUserId().equals(sysDept.getUserId()) ){
                CullenUtils.validateDataThrowException(true, "该分公司: " + sysDept.getDeptName() + " 已存在管理员：" + sysDept.getLeader() + "！");
            }

            if (selectUser.getEmployeeType() == 1) {
                //添加银行账户信息
                Account selectAccount = accountService.selectAccountByUserId(user.getUserId());
                if (selectAccount == null) {
                    Account account = new Account();
                    account.setUserId(user.getUserId());
                    account.setOpenName(user.getOpenName());
                    account.setOpeningBank(user.getOpeningBank());
                    account.setBankAccount(user.getBankAccount());
                    account.setCreditGold(user.getCreditGold());
                    accountService.insertAccount(account);
                } else {
                    selectAccount.setOpenName(user.getOpenName());
                    selectAccount.setOpeningBank(user.getOpeningBank());
                    selectAccount.setBankAccount(user.getBankAccount());
                    selectAccount.setCreditGold(user.getCreditGold());
                    accountService.updateAccount(selectAccount);
                }
                //是否修改保证金
                FundDetails selectFundDetails = fundDetailsService.selectFundDetailsByUserId(user.getUserId());
                if (selectFundDetails != null) {
                    if (selectFundDetails.getVariableAmount().compareTo(user.getCreditGold()) != 0) {
                        selectFundDetails.setVariableAmount(user.getCreditGold());
                        fundDetailsService.updateFundDetails(selectFundDetails);
                    }
                } else {
                    //添加资金明细（保证金）
                    FundDetails fundDetails = new FundDetails();
                    SysDept companyDept = sysDeptService.selectDeptById(user.getCompanyId());
                    fundDetails.setUserId(user.getUserId());
                    fundDetails.setDeptId(companyDept.getDeptId());
                    fundDetails.setDeptName(companyDept.getDeptName());
                    fundDetails.setFundType(4);
                    fundDetails.setVariableAmount(user.getCreditGold());
                    fundDetailsService.insertFundDetails(fundDetails);
                }
            } else {
                        //添加银行账户及保证金信息
                        Account account = new Account();
                        account.setUserId(user.getUserId());
                        account.setOpenName(user.getOpenName());
                        account.setOpeningBank(user.getOpeningBank());
                        account.setBankAccount(user.getBankAccount());
                        BigDecimal credit = user.getCreditGold() == null ? new BigDecimal(0) : user.getCreditGold();
                        account.setCreditGold(credit);
                        accountService.insertAccount(account);

                        //添加资金明细（保证金）
                        FundDetails fundDetails = new FundDetails();
                        fundDetails.setUserId(user.getUserId());
                        fundDetails.setDeptId(sysDept.getDeptId());
                        fundDetails.setDeptName(sysDept.getDeptName());
                        fundDetails.setFundType(4);
                        fundDetails.setVariableAmount(credit);
                        fundDetailsService.insertFundDetails(fundDetails);

                        //添加该管理员为分公司负责人
                        sysDept.setUserId(user.getUserId());
                        sysDept.setLeader(user.getNickName());
                        sysDept.setPhone(user.getUserPhone());
                        sysDeptService.updateDept(sysDept);

            }
        }else {
            throw new ServiceException("角色为经销商,但是等级(level)不是1级");
        }
        return toAjax(sysUserService.updateUser(user));
    }

    /**
     * 还原或者转移用户
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/restoreOrTransfer")
    public AjaxResult restoreOrTransfer(@RequestBody List<RestoreOrTransferUserPo> userPoList) {
        for (RestoreOrTransferUserPo user : userPoList) {
            sysUserService.restoreOrTransfer(user);
        }
        return toAjax(1);
    }

    /**
     * 禁止登录或者充许登录
     * status 帐号状态（0正常 1停用）
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/updateStatus")
    public AjaxResult updateStatus(@RequestParam Long userId, String status) {
        sysUserService.updateStatus(userId, status);
        return toAjax(1);
    }

    /**
     * 修改用户区域
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @GetMapping("/updateUserRegion")
    public AjaxResult updateUserRegion(@RequestParam Long userId, Integer region) {
        sysUserService.updateUserRegion(userId, region);
        return toAjax(1);
    }

    /**
     * 修改用户抽佣明细（签约比例）
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @GetMapping("/updateUserSigningRatio")
    public AjaxResult updateUserSigningRatio(@RequestParam Long userId, Integer signingRatio) {
        sysUserService.updateUserSigningRatio(userId, signingRatio);
        return toAjax(1);
    }

    /**
     * 客户转移
     * transferUserId 需要转移的用户ID
     * userId 用户id(转移到此用户ID)
     * type 1-转移客户，2转移订单，3都转移
     */
    @Log(title = "用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/userTransfer")
    public AjaxResult userTransfer(@RequestParam Long userId, Long transferUserId, Integer type) {
        sysUserService.userTransfer(userId, transferUserId, type);
        return toAjax(1);
    }

    /**
     * 删除用户信息
     */
    @Log(title = "用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(sysUserService.deleteUserByIds(userIds));
    }


    /**
     * 后管端客户预查
     */
    @GetMapping("/customer")
    public AjaxResult customer(SysUser sysUser) {
        return success(sysUserService.customer(sysUser));
    }

}
